package blocks

import (
	"fmt"
	"log"
	"math/big"

	"github.com/FISCO-BCOS/go-sdk/client"
	"github.com/FISCO-BCOS/go-sdk/conf"
	"github.com/ethereum/go-ethereum/common"
)

var mycli *client.Client
var mytask *Task

type UserTask struct {
	TaskName string `json:"task_name"`
	Bonus    int64  `json:"bonus"`
	Status   uint8  `json:"task_status"`
	Comment  string `json:"comment"`
	TaskID   string `json:"task_id"`
	Worker   string `json:"task_user"`
	Issuer   string `json:"issuer"`
}

func init() {
	configs, err := conf.ParseConfigFile("config.toml")
	if err != nil {
		log.Fatalf("ParseConfigFile failed, err: %v", err)
	}

	client, err := client.Dial(&configs[0])
	if err != nil {
		log.Fatal(err)
	}
	mycli = client

	instance, err := NewTask(common.HexToAddress("0x81454bd82d6e957a0e848179d98c9947f9203ee7"), client)
	if err != nil {
		log.Panic("failed to NewTask", err)
	}

	mytask = instance
}

func Register(username, password string) error {
	_, _, err := mytask.Register(mycli.GetTransactOpts(), username, password)
	return err
}

func Login(username, password string) (bool, error) {
	return mytask.Login(mycli.GetCallOpts(), username, password)
}

func Issue(username, password, desc string, bonus int64) error {
	_, _, err := mytask.Issue(mycli.GetTransactOpts(), username, password, desc, big.NewInt(bonus))
	return err
}

/*
	status 1: 接受任务
		   2: 提交任务
		   3: 确认任务通过
		   4: 任务退回，实际调用时传1
*/

func Update(username, password, comment string, status uint8, taskid int64) error {

	var err error
	if status == 1 {
		//接受任务
		_, _, err = mytask.Take(mycli.GetTransactOpts(), big.NewInt(taskid), username, password)
	} else if status == 2 {
		//提交任务
		_, _, err = mytask.Commit(mycli.GetTransactOpts(), big.NewInt(taskid), username, password)
	} else if status == 3 || status == 4 {
		//确认任务
		flag := true
		if status == 4 {
			flag = false
		}
		_, _, err = mytask.Confirm(mycli.GetTransactOpts(), big.NewInt(taskid), username, password, comment, flag)
	}

	return err
}

func Tasklist() ([]UserTask, error) {
	var tasks []UserTask
	//(issuer_s, worker_s, desc_s, comment_s, status_s, bonus_s);
	issuers, workers, descs, comments, statuss, bonuss, err := mytask.QryAlltasks(mycli.GetCallOpts())
	if err != nil {
		fmt.Println("failed to QryAlltasks", err)
		return tasks, err
	}
	var task UserTask
	for k, v := range issuers {
		task.Issuer = v
		task.TaskID = fmt.Sprintf("%d", k)
		task.Worker = workers[k]
		task.TaskName = descs[k]
		task.Comment = comments[k]
		task.Status = statuss[k]
		task.Bonus = bonuss[k].Int64()

		tasks = append(tasks, task)
	}

	return tasks, nil
}
